﻿using KPIS.GERP.Models;
using KPIS.GERP.Models.ICM;
using KPIS.GERP.Models.SYS;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.ServiceModel;
using System.Web.Mvc;

namespace KPIS.GERP.WCF.GIMS
{

    [ServiceContract]
    public interface IPurchaseRequestItemService
    {
        [OperationContract]
        IEnumerable<PurchaseRequestItem> Select(PurchaseRequestItem criteriaModel = null, List<string> includeSubObjectString = null);

        [OperationContract]
        IEnumerable<SelectListItem> SelectList(PurchaseRequestItem criteriaModel = null);

        [OperationContract]
        int Insert(PurchaseRequestItem model, int createByUserId);

        [OperationContract]
        void Update(PurchaseRequestItem model, int updateByUserId);

        [OperationContract]
        void Delete(int id, int deleteByUserId); 
    }

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "PurchaseRequestItemItemService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select PurchaseRequestItemItemService.svc or PurchaseRequestItemItemService.svc.cs at the Solution Explorer and start debugging.
    [System.ServiceModel.Activation.AspNetCompatibilityRequirements(
     RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)]
    public class PurchaseRequestItemService : IPurchaseRequestItemService
    {
        public IEnumerable<PurchaseRequestItem> Select(PurchaseRequestItem criteriaModel = null, List<string> includeSubObjectString = null)
        {
            try
            {
                using (var context = new GERPContext(false))
                {
                    IQueryable<PurchaseRequestItem> query = context.PurchaseRequestItems;

                    if (includeSubObjectString != null)
                    {
                        query = includeSubObjectString.Aggregate(query, (current, includePath) => current.Include(includePath));
                    }

                    if (criteriaModel != null)
                    {
                        object[] param;
                        query = query.Where(KPIS.GERP.Models.Class.Utility.GenerateWhereString(criteriaModel, out param), param);
                    }

                    var x = query.ToList();
                    return x;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public IEnumerable<SelectListItem> SelectList(PurchaseRequestItem criteriaModel = null)
        {
            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = "ไม่ระบุ", Value = "" });

            try
            {
                using (var context = new GERPContext(false))
                {
                    IQueryable<PurchaseRequestItem> query = context.PurchaseRequestItems.Include("MasResourceItem").Include("MasBudgetExpense");

                    if (criteriaModel != null)
                    {
                        object[] param;
                        query = query.Where(KPIS.GERP.Models.Class.Utility.GenerateWhereString(criteriaModel, out param), param);
                    }

                    var x = query.ToList();
                    foreach (var model in x)
                    {
                        var item = new SelectListItem { Text = (model.ResItemId != null ? model.MasResourceItem.Name : model.MasBudgetExpense.Name )
                            , Value = model.PrItemId.ToString() };
                        list.Add(item);
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return list;
        }

        public int Insert(PurchaseRequestItem model, int createByUserId)
        {
            try
            {
                using (var context = new GERPContext())
                {
                    model.RecordStatus = RecordStatus.WaitStatus;
                    model.CreatedBy = createByUserId;
                    model.CreatedWhen = DateTime.Now;
                    context.PurchaseRequestItems.Add(model);
                    context.SaveChanges();

                    return model.PrItemId;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Update(PurchaseRequestItem model, int updateByUserId)
        {
            try
            {
                using (var context = new GERPContext())
                {
                    context.Entry(model).State = EntityState.Modified;
                    model.UpdatedBy = updateByUserId;
                    model.UpdatedWhen = DateTime.Now;
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Delete(int id, int deleteByUserId)
        {
            try
            {
                using (var context = new GERPContext(true))
                {
                    var modelToDelete = context.PurchaseRequestItems.Find(id);
                    if (modelToDelete == null) return;

                    modelToDelete.RecordStatus = RecordStatus.DeletedStatus;
                    modelToDelete.UpdatedBy = deleteByUserId;
                    modelToDelete.UpdatedWhen = DateTime.Now;
                    context.SaveChanges();
                       
                    var pprItems = context.PrePurchaseRequestItems.Where(m => m.PrItemId == modelToDelete.PrItemId).ToList(); 

                    foreach (var pprItem in pprItems)
                    {
                        pprItem.PrItemId = null;
                        context.SaveChanges();
                    }  
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
